<?php
          class ApiCenter_ProductApi_Model_Upload_Api_V2 extends ApiCenter_ProductApi_Model_Upload_Api{
             
              /*
               * 版本版本上线  2016-08-04
               *
               * */
              protected  $result = array(
                  
              );   
              protected  $need_filter = array(
                                      "name",
                                      "description",
                                      "short_description",
                                      );
              protected  $res_product = array(
              
              );
              protected  $no_required = array(
            "common_reasons",//拒绝原因'字段，新增时不可见
           "pulscen",
            "common_warehouse_code",
           "price_view",
            "giftcard_amounts",
           "allow_open_amount",
           "common_weight",
           "open_amount_min",
           "open_amount_max",
           "group_price",
           "tier_price",
           "common_supply_price",
           "msrp_enabled",
           "msrp_display_actual_price_type",
           "common_supplier_special_price",
             "attr_giftcard_amounts",
            "fb_product",
           "news_from_date",
           "news_to_date",
           "url_key",
           "country_of_manufacture",
           "is_returnable",
           "em_featured",
           "em_deal",
           "em_hot",
           "yml",
            "sku",
           "vendor_id",
            "visibility",
           "status",
           //"approval",
           "cost",
           "yandex_market_product_category",
           "tax_class_id",
           "tiers_table",
           "msrp",
           "common_other_shipping_type",
           "common_publish_platform",
           "common_shipping_method",
           "common_dimensional_weight",
           "inventory_manage_stock",
           "inventory_min_sale_qty",
           "inventory_max_sale_qty",
           "inventory_is_qty_decimal",
           "inventory_notify_stock_qty",
           "inventory_enable_qty_increments",
           "inventory_backorders",
           "simple_product_visibility",
              );
              protected  $required_fields = array(            
                           "stock_data",
                          "category"
              );
              
              private   $additional ="Additional Product Information";
              
            
              const DEFULT_VISIBILITY = "1";
               
              const DEFULT_STAUTS = "2";
               
              const NO_SUBMIT = "0";
              
              const  WEBSITEID = "1";
              
              const PAGE_SIZE_DEFAULT =10;
              
              const PAGE_SIZE_MAX = 100;
              
              const  CN = 3;
              
              const PENDDING = 1;
   
              protected $_websites = array(
                 "1",
              );
              /**
               * 默认和处理某些字段
               *
               */
              protected  function _filterValue($data,$type,$set_id,$vendor_info,$close=false) {
                  $dataPrice = "";//计算运费的参数

                  if($data['approval']>1){
                      $data['approval']  = self::NO_SUBMIT;
                  }
                  $data['tax_class_id'] = 0;
                  $data['status']   =    self::DEFULT_STAUTS;
                  $data['websites'] =  $this->_websites;
                  $data['vendor_id'] = $vendor_info['entity_id'];
                  //是否关闭字段验证功能
                  if(!$close){
                      
                      if(!isset($vendor_info['warehouse_code'])){
                          $this->_fault('not found default warehousecode,please set!');
                      }else{
                          $productData['common_warehouse_code'] = $vendor_info['warehouse_code'];
                      }
                      
                      //获取相关需要填写的属性
                      $required_fields = json_decode($this -> getRequriedFiled($set_id),true);
                      $required_field = $required_fields['info']['required_attr'];
                      foreach ($required_field as $key => $val){
                          $this->required_fields[]=$val['code'];
                      }
                      
                      if(!empty($data['common_is_charged'])){
                          $this->required_fields[] = "common_msds";
                      }
                      if ($type=="configurable"){
                          $data['stock_data']= array(
                                     'manage_stock' => 0, //manage stock
                                     'use_config_manage_stock' => 0,
                             );
                      }
                       
                       
                      foreach($this ->required_fields as $v){
                          if(!isset($data[$v])){
                              $error[]=$v."字段为必填字段";
                          }   
                          if(!empty( $error)){
                              $error=implode(",",$error);
                              $this->_fault($error);
                          }
                      }
                  }
                  return $data;
              }
              /**
               *   prdocut tovalidate and save
               *    @param $vendors_info
               *   @param $type
               *   @param $set
               *   @param $vendor_sku
               * @param $productData array
               * @return   $id
               * */
              public  function validateProduct($vendors_info,$type,$set,$vendor_sku,$productData,$store = null ) {
                  try {
                      if (!$type || !$set || !$vendor_sku ) {
                          $this->_fault('data_invalid');
                      }

                      
                      Mage::log(1);
                      $productData = $this->_filterValue($productData,$type,$set,$vendors_info);
                       
                      if($productData['sku']){
                          unset($productData['sku']);
                      }
                      if($productData['set_id']){
                          unset($productData['set_id']);
                      }
                      $entity_id = $vendors_info['entity_id'];
                      $vendor_id = $vendors_info['vendor_id'];
                      $sku_final = $vendor_id."_".$vendor_sku;
                      $this->_checkProductTypeExists($type);
                      $this->_checkProductAttributeSet($set);
                      /** @var $product Mage_Catalog_Model_Product */
                      $product = Mage::getModel('catalog/product');
                      $product->setStoreId($this->_getStoreId($store))
                      ->setAttributeSetId($set)
                      ->setTypeId($type)
                      ->setSku( $sku_final);
              
                      if (!$productData['stock_data']) {
                          //Set default stock_data if not exist in product data
                          $_stockData = array('use_config_manage_stock' => 0);
                          $product->setStockData($_stockData);
                      }
                      if($productData['images']['image']){
                          $imageFileData = $productData['images']['image'];
                          unset($productData['images']);
                           
                          if($this ->arrayLevel($imageFileData)>1){
                              foreach ($imageFileData as $v){
                                  $productData['media_gallery']['images'][]=$v;
                              }
                          }else{
                              $productData['media_gallery']['images'][]=$imageFileData;
                          }
                      }
                      Mage::log(3);
                      if(!isset($productData['media_gallery'])||!is_array($productData['media_gallery'])){
                          foreach ($product->getMediaAttributes() as $mediaAttribute) {
                              $mediaAttrCode = $mediaAttribute->getAttributeCode();
                              $product->setData($mediaAttrCode, 'no_selection');
                          }
                      }
                      $this->_prepareDataForSave($product, $productData,$type);
                      Mage::log(4);
                      $strErrors =array();
              
              
                      //捕捉验证错误，不能正常使用
                      if (is_array($errors = $product->validate())) {
                          $strErrors = array();
                          foreach($errors as $code => $error) {
                              if ($error === true) {
                                  $error = Mage::helper('catalog')->__('Attribute "%s" is invalid.', $code);
                              }
                              $strErrors = $error;
                          }
                          $error=implode(",",$error);
                          $this->_fault($error);
                      }
                      $product->save();
                      return $product->getId();
                  } catch (Exception $e) {
                      return $e->getMessage();
                  }
              }
              
          /**
           *  返回超级属性所需的选项值
           **/
          public function superAttributesOption($set_id){
          
                  $attributes = Mage::getModel('catalog/product_attribute_api')->items($set_id);
                  foreach($attributes as $_attribute)
                  {
                      if($_attribute['scope'] == 'global' && $_attribute['type'] == 'select')
                      {
                          $super_attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$_attribute['code']);
                          if($super_attribute->getIsConfigurable() == 1)
                          {
                              $attr['code'] = $super_attribute->getAttributeCode();
                              $attr['fronted_label'] =$super_attribute->getFrontendLabel();
                              $attr['option'] = $this->getAttributesOption($super_attribute->getAttributeId());
                              $this->result[]=  $attr;
                          }
                      }
                  }
                  return json_encode($this->result);
              }
              
              public  function getRequriedFiled($set_id) {
                  $required_attributes = array(); 
                  $attributes = array();
                   try {
                       
                      $this->_checkProductAttributeSet($set_id);
                         
                      $collection = Mage::getResourceModel('catalog/product_attribute_collection')
                        ->addStoreLabel(self::CN)
                        ->setAttributeSetFilter($set_id)
                        ->addVisibleFilter();
                         $collection->getSelect()
                                         ->joinLeft(array("k"=>"eav_attribute_group"),
                                                       "k.attribute_group_id = entity_attribute.attribute_group_id",
                                                        array("group_name"=>"k.attribute_group_name")
                                              );
                        

                         $attributes = $collection->getData();
                         if(empty($attributes)){
                             $this->_fault("can not query to fileds!");
                         }
 
                         } catch (Exception $e) {
                             $this->result['status'] = "error";
                             $this->result['info'] = $e->getMessage();
                         }
                 foreach ($attributes as $key => $val){
                     foreach ($this ->no_required as $filed){
                         if($val['attribute_code']==$filed){
                             unset($attributes[$key]);
                         }
                     }
                 }
                 $attr = array();
                 $attr1 = array();
                  foreach ($attributes as $key => $val){         
                      if($val['is_required']== 1){
                           $attr['code'] = $val['attribute_code'];
                           $attr['type'] = $val['frontend_input']; 
                           if($val['frontend_input']== "select"||$val['frontend_input']== "multiselect"){
                              $attr['select_options']= $this->getAttributesOption($val['attribute_id']);
                             }else{
                                 unset($attr['select_options']);
                             }
                             $required_attributes["required_attr"][] = $attr;    

                       }else{
                           if($val['group_name'] == $this->additional){
                               $attr1['code'] = $val['attribute_code'];
                               $attr1['type'] = $val['frontend_input'];
                               if($val['frontend_input']== "select"||$val['frontend_input']== "multiselect"){
                                   $attr1['select_options']= $this->getAttributesOption($val['attribute_id']);
                               }else{
                                   unset($attr1['select_options']);
                               }
                               $required_attributes['additional_attr'][] =  $attr1;
                           } 
                        
                       }
                  }
                  $required_attributes["required_attr"][]=array(
                      "code"=>"approval",
                       "type"=>"select",
                      "select_options"=>array(
                          array(
                              "value"=>"0",
                              "label"=>"Not Submited"
                          ),
                          array(
                              "value"=>"1",
                              "label"=>"Pending"
                          ),
                      )
                  );
                $result['status'] = "success";
                $result['info'] = $required_attributes;
                 return json_encode($result);
              }
              public function getAttributeSet(){
                  $entityType = Mage::getModel('catalog/product')->getResource()->getEntityType();
                  $collection = Mage::getResourceModel('eav/entity_attribute_set_collection')
                  ->setEntityTypeFilter($entityType->getId());
                  
                  $result = array();
                  foreach ($collection as $attributeSet) {
                      $this->result[] = array(
                          'set_id' => $attributeSet->getId(),
                          'name'   => $attributeSet->getAttributeSetName()
                      );
                  }
              
                  return json_encode( $this->result);
              }
              
            /**
              *  批量添加简单商品
              * 
               **/
           public function uploadSimple($productData,$login){
            try {
              $this->result['status'] = "success";
              $login = json_decode($login,true);

             $vendor_info = $this->validateVendors($login['username'], $login['password']);
               if(!is_array($vendor_info)){
                    $this->_fault("vendor_invalid");
               }
               
               $productData = $this->makeXmlToarr($productData);
         
               if(!$productData){
                   $this->_fault('xml File format error');
               }
               $is_arrays = false;
               foreach ($productData['simple'] as  $key => $product){
                   if(is_numeric($key)){
                       $is_arrays = true;
                       //返回子产片所有的id
                    $this->result['info']['returnId'][]= $this->validateProduct($vendor_info,'simple',$product['set_id'],$product['vendor_sku'],$product);
                   }
               
               }
               if(!$is_arrays){
                   $product = $productData['simple'];
                 $this->result['info']['returnId'][]= $this->validateProduct($vendor_info,'simple',$product['set_id'],$product['vendor_sku'],$product);
               }
               
              
                 return json_encode($this->result);
                 } catch (Mage_Core_Exception $e) {
                     $this->result['status'] = "error";
                     $this->result['info'] = $e->getMessage();           
                   return json_encode($this->result);
                 }
           }
     
           /**
            *  批量添加配置商品
            **/
           
           public function uploadConfigurable($productData,$login){
           $this->result['status'] = "error";
           try {
              $login = json_decode($login,true);

             $vendor_info = $this->validateVendors($login['username'], $login['password']);
               if(!is_array($vendor_info)){
                    $this->_fault('vendor_invalid');
               }
               
               $productData = $this->makeXmlToarr($productData);
         
               if(!$productData){
                    $this->_fault('xml File format error','');
               }
                if(empty($productData['child_products']['child_product'])){
                    $this->_fault('configurable File format error','');
                }
                $is_arrays = false;
                 foreach ($productData['child_products']['child_product'] as  $key => $product){ 
                     $product['visibility'] =1;
                     if(is_numeric($key)){
                         $is_arrays = true;
                         //返回子产片所有的id
                         $simpleProductArr[]= $this->validateProduct($vendor_info,'simple',$productData['set_id'],$product['vendor_sku'],$product);
                     }
                    
               }
               if(!$is_arrays){
                   $product = $productData['child_products']['child_product'];
                   $product['visibility'] =1;
                   $simpleProductArr[]= $this->validateProduct($vendor_info,'simple',$productData['set_id'],$product['vendor_sku'],$product);
               }
               $simpleProducts = Mage::getResourceModel('catalog/product_collection')
               ->addIdFilter($simpleProductArr);
               $productDataInfo = $this->getConfigAttrCode($productData['set_id'],$productData['select_Attributes']['select_Attribute'],$simpleProductArr);               
            
               $productData['configurable_attributes_data']=$productDataInfo['configurable_attributes_data'];
               $productData['configurable_products_data']=$productDataInfo['configurable_products_data'];
               $productData['can_save_configurable_attributes'] = true;
               $configurableSetId =$productData['set_id'];
               unset($productData['set_id']);
               $configurableSku =$productData['vendor_sku'];
               unset($productData['child_product']);
              
               $configurableId = 0;
               try {
                   $configurableId = $this->validateProduct($vendor_info,'configurable',$configurableSetId,$configurableSku,$productData);
                    if(!is_numeric($configurableId)){ 
                        $this->_fault("configurable Product fails : ".$configurableId);
                    }
               } catch (Exception $e) {
                   $this->deleteProduct($simpleProductArr);
                   $this->result['status'] = "error";
                   $this->result['info'] = $e->getMessage();
                   return json_encode($this->result);
               }
               $this->result['status'] = "success";
               $this->result["info"]["configurableId"] = $configurableId;  
               $this->result["info"]["childId"] =$simpleProductArr;
               
               } catch (Mage_Core_Exception $e) {
                   $this->result['status'] = "error";
                   $this->result['info'] = $e->getMessage();
               }
               return json_encode($this->result);
           }
           


            public function update($product, $productData, $type,$store = null, $identifierType = null)
            {
                $this->_prepareDataForSave($product, $productData,$type);
            
                try {
                    /**
                     * @todo implement full validation process with errors returning which are ignoring now
                     * @todo see Mage_Catalog_Model_Product::validate()
                     */
                    if (is_array($errors = $product->validate())) {
                        $strErrors = array();
                        foreach($errors as $code => $error) {
                            if ($error === true) {
                                $error = Mage::helper('catalog')->__('Value for "%s" is invalid.', $code);
                            } else {
                                $error = Mage::helper('catalog')->__('Value for "%s" is invalid: %s', $code, $error);
                            }
                            $strErrors[] = $error;
                        }
                        $this->_fault('data_invalid', implode("\n", $strErrors));
                    }
            
                    $product->save();
                } catch (Exception $e) {
                     return $e->getMessage();
                }
            
                return true;
            }
          
            public function queryProductInfo($product_id,$login){
                try{
                    $login = json_decode($login,true);
                
                    $vendor_info = $this->validateVendors($login['username'], $login['password']);
                    if(!is_array($vendor_info)){
                        $this->_fault('vendor_invalid');
                    }
                   $resData = $this->_getProductInfo($product_id, $vendor_info);
                   $this->result['status'] = "success";
                   $this->result['info'] = $resData;
                   return json_encode($this->result);
                }catch(Mage_Core_Exception $e){
                    $this->result['status'] = "error";
                    $this->result['info'] = $e->getMessage();
                    return json_encode($this->result);
                }
            }
            public function queryAllProduct($login,$pageNumber,$pageSize){
                    try{
                        $login = json_decode($login,true);
                        
                        
                        if ($pageNumber != abs($pageNumber)) {
                            $this->_fault("'Resource collection paging error");
                        }
                        
                        if (null == $pageSize) {
                            $pageSize = self::PAGE_SIZE_DEFAULT;
                        } else {
                            if ($pageSize != abs($pageSize) || $pageSize > self::PAGE_SIZE_MAX) {
                                $this->_fault("'The paging limit exceeds the allowed number.");
                            }
                        }
                        $vendor_info = $this->validateVendors($login['username'], $login['password']);
                        if(!is_array($vendor_info)){
                            $this->_fault('vendor_invalid');
                        }
                        
                        $collection = Mage::getResourceModel('catalog/product_collection')
                        ->addAttributeToFilter('vendor_id', array('in' =>$vendor_info['entity_id']));
                        
                       $total = count($collection);
                        $collection->setCurPage($pageNumber)->setPageSize($pageSize);
                        
                        $productData = $collection ->getData();
                        
                        if(!$productData){
                            $this->_fault('There is no query to the goods');
                        }
                        
                        foreach ($productData as $val){   
                            $resData[] =$this->_getProductInfo($val['entity_id'],$vendor_info)            ;
                        } 
                   
                        $this->result['status'] = "success";
                        $this->result['info'] = $resData;
                        $this->result['total'] = $total;
                        return json_encode($this->result);
                }catch(Mage_Core_Exception $e){
                    $this->result['status'] = "error";
                    $this->result['info'] = $e->getMessage();
                    return json_encode($this->result);
                }
            }
            
            public function updatePrice($product_id,$productData,$login){
                try{
                    $login = json_decode($login,true);
                    
                    $vendor_info = $this->validateVendors($login['username'], $login['password']);
                    if(!is_array($vendor_info)){
                        $this->_fault('vendor_invalid');
                    }
                  
                    $productData = $this->makeXmlToarr($productData);
                    
                    if(!$productData){
                        $this->_fault('xml File format error','');
                    }
                   //此处允许商家即可以传商品id 又可以传SKu 
                 if (is_string($product_id) && !preg_match("/^[+-]?[1-9][0-9]*$|^0$/", $product_id)) {
                        $product_id=$vendor_info['vendor_id']."_".$product_id;
                    }
                    $product = $this->_getProduct($product_id, $store=null, $identifierType=null);
                    $type =$product->getTypeId();
                    if($product->getVendorId()!=$vendor_info['entity_id']){ $this->_fault('The goods do not belong to you or no existing');}
                    $stock_model=$product->getStockItem();   
                    $info['price']=$productData['price']&&is_numeric($productData['price'])?(int)$productData['price']:$product->getPrice();
             
                    $info['stock_data']['qty']=isset($productData['qty'])?$productData['qty']:$stock_model->getQty(); 
                    $info['stock_data']['is_in_stock']=isset($productData['is_in_stock'])?$productData['is_in_stock']:$stock_model->getIsInStock();
                    if($type=="configurable"){
                        unset($info['stock_data']);
                    }
                    //修改组产品下面的子产品价格
//                     if($configurable&&isset($productData['common_supply_price'])){
//                         $parent_product = $this->_getProduct($product_id, $store=null, $identifierType=null);
                        
//                     }else{
//                         $info['price'] = $productData['common_supply_price']? $info['common_supply_price']+$cost:$product->getPrice();
//                     }
                    //如果库存为0自动下架
                    if($info['stock_data']['qty']=="0"){
                        $info['stock_data']['is_in_stock'] = "0";
                    }else{
                        $info['stock_data']['is_in_stock'] = "1";
                    }
                     $this->update($product,$info,$type);
                     $this->result['status'] = "success";
                     $this->result['info'] = "修改成功";
                      return json_encode($this->result);
                  }catch(Mage_Core_Exception $e){
                      $this->result['status'] = "error";
                      $this->result['info'] = $e->getMessage();
                      return json_encode($this->result);
                  }
             }
             
             /**
              * 上传产品图片
              * 
              * */
             public function uploadImages($images){
                  $tmpPath = Mage::getBaseUrl("media")."tmp".DS."catalog".DS."product";
                  $images = json_decode($images,true);
                  $product = Mage::getModel("catalog/product");
                 try {
                     
                     if(empty($images)||!is_array($images)||$this->arrayLevel($images)!=2){
                         $this->_fault("info format error! ");
                     }
                     foreach ($images as $_image){
                         $path []= $tmpPath.$this->uploadImage($product, $_image);
                     }
                     $this->result['status'] = "success";
                     $this->result['info']['file'] = $path;
                     $this->result['info']['path_prefix'] = $tmpPath;
                     return json_encode($this->result);
                     
                 }catch(Mage_Core_Exception $e){
                     $this->result['status'] = "error";
                     $this->result['info'] = $e->getMessage();
                     return json_encode($this->result);
                 }
             }
             
             /**
              * 获取所有类目 以及所属的所开放属性集
              *
              * */
             public function  getAllCategory(){
                   $tree =  Mage::helper("productapi/categorytree")->getCategoryTree(false);
                  try {
                      if(empty($tree)){
                          $this->_fault("category is not found!");
                      }
                      $this->result['status'] = "success";
                      $this->result['info']= $tree;
                  } catch (Exception $e) {
                      $this->result['status'] = "error";
                      $this->result['info'] = $e->getMessage();
                  }
                  return json_encode($this->result);
             }
             
          }